<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row class="choose_cate">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectdCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->

      <!-- 动态参数标签页 -->
      <el-tabs v-model="activeName" @tab-click="tabsHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加参数</el-button
          >

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- v-for获取标签列表 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="closeTagData(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- input button添加tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column
              prop="attr_name"
              label="动态参数"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-edit"
                  @click="removeParamData(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态参数标签页 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- v-for获取标签列表 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="closeTagData(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- input button添加tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column
              prop="attr_name"
              label="静态属性"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-edit"
                  @click="removeParamData(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + addParamType"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeAddDialogVisible"
    >
      <el-form
        :model="addForm"
        :rules="addFormRoles"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="addParamType" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'添加' + addParamType"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeEditDialogVisible"
    >
      <el-form
        :model="editForm"
        :rules="editFormRoles"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="addParamType" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      //   商品列表
      cateList: [],
      //   选择的种类的id
      selectdCateKeys: [],
      //   级联选择器对应的配置选项
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //   当前选中的标签name
      activeName: 'many',
      //   动态参数的数据
      manyTableData: [],
      //   静态属性的数据
      onlyTableData: [],
      // 是否开启添加参数的对话框
      addDialogVisible: false,
      // 需要添加参数或者属性信息
      addForm: {
        attr_name: '',
      },
      // 需要添加参数或者属性信息规则
      addFormRoles: {
        attr_name: [
          {
            required: true,
            message: `内容不能为空`,
            trigger: 'blur',
          },
        ],
      },
      // 是否开启修改对话框
      editDialogVisible: false,
      //  需要修改的参数或者属性信息
      editForm: {
        attr_name: '',
      },
      //  需要修改的参数或者属性信息规则
      editFormRoles: {
        attr_name: [
          {
            required: true,
            message: `内容不能为空`,
            trigger: 'blur',
          },
        ],
      },
      // 当前属性 ID
      attr_id: '',
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //   获取商品列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品列表信息失败')
      this.cateList = res.data
    },
    // 级联选择器改变后触发
    handleChange() {
      this.getParamsData()
    },
    // 点击标签调用的函数
    tabsHandleClick() {
      this.getParamsData()
    },
    // 获取参数的数据
    async getParamsData() {
      // 判断选择的是不是三级类别
      if (this.selectdCateKeys.length !== 3) {
        this.selectdCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 确定了类别之后  获取参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      // 将字符串attr_vals转换为数组

      res.data.forEach((item) => {
        item.attr_vals =
          item.attr_vals.length > 0 ? item.attr_vals.split(' ') : []
        // 将inputVisible 和 inputValue放在item上
        item.inputVisible = false //是否显示input
        item.inputValue = '' //input的值
      })
      //   根据页面  返回不同的数据到不同的data属性
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 关闭添加参数的对话框，清空form的数据
    closeAddDialogVisible() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加属性到数据库
    addParamData() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加失败')

        // 添加成功
        this.$message.success('添加成功')
        this.addDialogVisible = false
        // 重新获取参数的数据
        this.getParamsData()
      })
    },
    // 展示修改参数的对话框
    showEditDialog(scope) {
      this.attr_id = scope.attr_id
      this.editForm.attr_name = scope.attr_name

      this.editDialogVisible = true
    },
    // 关闭修改参数的对话框 清空from表单
    closeEditDialogVisible() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改数据库参数数据
    editParamData() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return

        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) return this.$message.error('更新失败')

        this.$message.success('更新成功')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除属性
    async removeParamData(attr_id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmRes !== 'confirm') {
        return this.$message.info('您取消了删除操作！')
      }
      // 确定删除
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')

      this.$message.success('删除成功')
      this.getParamsData()
    },
    // 摁回车或者鼠标移出input的事件
    handleInputConfirm(scope) {
      // 判断文本框的内容是否有效
      if (scope.inputValue.trim().length === 0) {
        scope.inputValue = ''
        // 隐藏input框
        scope.inputVisible = false
        return
      }
      // 如果有效则添加到attr_vals
      scope.attr_vals.push(scope.inputValue.trim())
      scope.inputValue = ''
      scope.inputVisible = false
      console.log(scope.attr_vals)

      // 提交标签参数
      this.handlerTagData(scope)
    },
    // 点击显示input
    showInput(scope) {
      // 显示input框
      scope.inputVisible = true
      // input框出来后  自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag标签
    closeTagData(i, scope) {
      scope.attr_vals.splice(i, 1)
      this.handlerTagData(scope)
    },
    // 编辑提交标签参数
    async handlerTagData(scope) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${scope.attr_id}`,
        {
          attr_name: scope.attr_name,
          attr_sel: scope.attr_sel,
          attr_vals: scope.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('更新失败')
        return
      }

      this.$message.success('更新成功')
    },
  },
  computed: {
    //   计算是否禁用按钮
    isBtnDisabled() {
      if (this.selectdCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 计算当前选中的类别id
    cateId() {
      if (this.selectdCateKeys.length === 3) {
        return this.selectdCateKeys[2]
      }
      return null
    },
    // 计算当前是添加动态参数还是静态属性
    addParamType() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
  },
}
</script>

<style lang="less" scoped>
.choose_cate {
  margin: 15px 0;
}
.el-tag {
  margin-right: 20px;
}
.input-new-tag {
  width: 150px;
}
</style>